import os
import time
import shutil
from datetime import datetime

import yaml

from log import logger
def delete_directories_older_than_months(directory, months=3, ui_handle=None): # 20240625
    """
    删除指定目录下指定月份数以前的子目录及其内容。
    len(dir_name) == 8 and dir_name[:2] == '20' # 20240625

    :param directory: 要检查和清理的目录路径
    :param months: 要删除的目录的月份数
    """

    # 计算指定月份数之前的日期时间戳
    time_threshold = time.time() - (months * 30 * 24 * 60 * 60)

    for root, dirs, _ in os.walk(directory, topdown=False):  # topdown=False确保从子目录向上遍历
        for dir_name in dirs:
            if len(dir_name) == 8 and dir_name[:2] == '20': # 20240625
                dir_path = os.path.join(root, dir_name)
                # dir_mtime = os.path.getmtime(dir_path)
                # 根据文件夹名称计算时间戳
                # date_str = '20240625'
                date_format = '%Y%m%d'  # 定义日期字符串的格式
                dt_object = datetime.strptime(dir_name, date_format)# 将字符串转换为datetime对象
                dir_mtime = dt_object.timestamp()# 将datetime对象转换为时间戳
                # print(dir_path)
                # print(dir_mtime)
                if dir_mtime < time_threshold:

                    if ui_handle:
                        ui_handle.loginfo(f"删除文件夹: {dir_path}")
                    else:
                        logger.info(f"删除文件夹: {dir_path}")
                    try:
                        # os.rmdir(dir_path)  # 这里使用rmdir，它只能删除空目录
                        shutil.rmtree(dir_path) # 如果要递归删除非空目录，请使用shutil.rmtree
                    except OSError as e:
                        if ui_handle:
                            ui_handle.loginfo(f"删除文件夹错误: {e.filename} - {e.strerror}")
                        else:
                            logger.error(f"删除文件夹错误: {e.filename} - {e.strerror}")
def read_yaml(file_path):
    with open(file_path, 'r') as file:
        config = yaml.safe_load(file)
    return config


def write_yaml(data, file_path):
    with open(file_path, 'w') as file:
        yaml.safe_dump(data, file)

if __name__ == '__main__':

    # 使用示例
    directory_to_clean = r'D:\data\save\fuba_tianxian'  # 替换为你要清理的目录路径
    months_to_keep = 2 # 更改为你希望保留的月份数
    delete_directories_older_than_months(directory_to_clean, months_to_keep)
